package kov.core.body.zy
{
	import com.riaoo.events.AnimationEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	
	import kov.core.BodyState;
	import kov.core.IBody;
	import kov.core.StateCommand;
	import kov.core.body.StateEnum;
	import kov.core.global.Global;
	
	public class ZYPaoDa extends BodyState
	{
		[Embed("../../../../../assets/zy/paoda/0.gif")]
		private var Frame0:Class;
		[Embed("../../../../../assets/zy/paoda/1.gif")]
		private var Frame1:Class;
		[Embed("../../../../../assets/zy/paoda/2.gif")]
		private var Frame2:Class;
		[Embed("../../../../../assets/zy/paoda/3.gif")]
		private var Frame3:Class;
		[Embed("../../../../../assets/zy/paoda/4.gif")]
		private var Frame4:Class;
		
		public function ZYPaoDa(body:IBody, priority:int=1)
		{
			super(StateEnum.PAO_DA, body, priority);
			createRenderer();
		}
		
		// 创建渲染帧。
		private function createRenderer():void
		{
			var f0:BitmapData = (new Frame0() as Bitmap).bitmapData;
			var f1:BitmapData = (new Frame1() as Bitmap).bitmapData;
			var f2:BitmapData = (new Frame2() as Bitmap).bitmapData;
			var f3:BitmapData = (new Frame3() as Bitmap).bitmapData;
			var f4:BitmapData = (new Frame4() as Bitmap).bitmapData;
			this.renderer.push(f0);
			this.renderer.push(f1);
			this.renderer.push(f2);
			this.renderer.push(f3);
			this.renderer.push(f4);
		}
		
		override public function execute():void
		{
			this.body.renderer.frameSequence = this.renderer;
			this.body.renderer.delay = 70;
			this.body.renderer.offsetX = 66;
			this.body.renderer.offsetY = 84;
			this.body.renderer.gotoAndPlay(0);
			this.body.renderer.addEventListener(AnimationEvent.ANIMATION_END, onAnimationEnd);
			Global.stage.addEventListener(Event.ENTER_FRAME, loop);
		}
		
		override public function exit():void
		{
			this.body.renderer.removeEventListener(AnimationEvent.ANIMATION_END, onAnimationEnd);
			Global.stage.removeEventListener(Event.ENTER_FRAME, loop);
		}
		
		private function onAnimationEnd(event:AnimationEvent):void
		{
			var cmd:StateCommand = new StateCommand(StateEnum.XING_ZOU);
			this.body.executeStateCommand(cmd);
		}
		
		private function loop(event:Event):void
		{
			var toX:Number = this.body.x + (this.body.faceToLeft ? -3 : 3);
			if ( !Global.world.mapData.blockData.isBlock(toX, this.body.y) )
			{
				this.body.x = toX;
			}
		}
		
	}
}